
import { resetRouter } from '@/router'
import { getProfile } from '@/api/user'
import { login as userLogin, getUserDetailById } from '@/api/user'
import { getToken, setToken as saveToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken() || null,
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken(state, newToken) {
      state.token = newToken // 设置token
      // 把token做持久化,把token存储到本地
      saveToken(newToken)
    },
    // 删除token
    removeToken(state) {
      state.token = null // 删除vuex的token
    },
    setUserInfo(state, newInfo) {
      state.userInfo = newInfo
    }
  },
  actions: {
    async login(context, payload) {
      // console.log(context, payload)
      const res = await userLogin(payload)
      console.log(res)
      context.commit('setToken', res.data)
    },
    async getUserInfo(context) {
      // ajax获取数据
      const rs = await getProfile()
      console.log('用来获取用户信息的,', rs)
      const info = await getUserDetailById(rs.data.userId)
      context.commit('setUserInfo', { ...info.data, ...rs.data })
      return rs.data.roles.menus
    },
    logout(context) {
      // 删除本地token
      context.commit('setToken', '')
      // 清空vuex
      context.commit('setUserInfo', {})

      // 重置路由
      resetRouter()
    }
  }
}

